﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharp.Libs.WPF;
using System.Collections.ObjectModel;
using CSharp.Libs.Koc.UserControls.ItemClasses;
using CSharp.Libs.Koc.KernelModels;
using CSharp.Libs.Koc.Models;
using System.Threading;
using System.Collections;

namespace CSharp.Libs.Koc.UserControls
{
    partial class KocKnightLevelerViewModel : ViewModelBase
    {
        #region declarations
        private ObservableCollection<UserProfileItem> _ocUsers = new ObservableCollection<UserProfileItem>();

        private UserProfileItem _upiSelectedUser = null;

        private int _intServerId = 1;

        //constants
        private const string DEFAULT_WINDOW_TITLE = "Koc Knight Leveler ";
        #endregion



        #region constructor / finalizer
        private void _initKernelControl()
        {
            _KRNL.TM.ChatReceived += new TrafficMonitor.ChatReceivedEventHandler(TM_ChatReceived);

            int.TryParse(_KRNL.LAO.GetOption(constants.LAO_DEFAULT_SERVER_ID), out _intServerId);

            //Create empty Item to avoid errors. :)
            _upiSelectedUser = new UserProfileItem();
        }
        #endregion



        #region event handling
        void TM_ChatReceived(object sender, ChatReceivedEventArgs crea)
        {
            try
            {
                if (PhpCommandGenerator.Users.Count > _ocUsers.Count)
                {
                    _DISP.Invoke((Action)delegate
                    {
                        try
                        {
                            foreach (KeyValuePair<string, UserValidatorItem> kvpUser in PhpCommandGenerator.Users)
                            {
                                if (!_usersContainsFbUid(kvpUser.Value.FbUid))
                                {
                                    UserValidatorItem UVI = kvpUser.Value;
                                    UserProfileItem UPI = new UserProfileItem();
                                    UPI.UVI = UVI;

                                    Thread thr = new Thread((ParameterizedThreadStart)delegate
                                    {
                                        _getUserAlliance(ref UPI);
                                    });
                                    thr.Start();

                                    _ocUsers.Add(UPI);
                                    OnPropertyChanged("Users");
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion



        #region private functions
        /// <summary>_usersContainsFbUid</summary>
        /// <param name="FbUid"></param>
        /// <returns></returns>
        /// <history>04.02.2012</history>
        private bool _usersContainsFbUid(
            string FbUid)
        {
            foreach (UserProfileItem UPI in _ocUsers)
            {
                if (UPI.FbUid == FbUid)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>_getUserAlliance</summary>
        /// <history>03.02.2012</history>
        /// <history>modified 09.02.2012: changed handlig of Profile Item</history>
        private void _getUserAlliance(
            ref UserProfileItem UPI)
        {
            if (UPI != null && UPI.UVI != null && PhpCommandGenerator.IsInitialized)
            {
                //First off clear data
                UPI.Clear();

                //get viewCourt
                using (PhpCommand pcDispatch = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands._dispatch, _intServerId, UPI.FbUid))
                {
                    //Check if viewCourt command was generated
                    if (pcDispatch == null)
                    {
                        return;
                    }

                    //set needed parameters
                    pcDispatch.Parameters.Add(PhpCommandParameters.USER_ID, pcDispatch.Parameters[PhpCommandParameters.TV_UID]);
                    pcDispatch.Parameters[PhpCommandParameters.CTRL] = "PlayerProfile";
                    pcDispatch.Parameters[PhpCommandParameters.ACTION] = "get";

                    //get result
                    Hashtable htUserViewCourt = null;
                    pcDispatch.GetAnswerHashtable(out htUserViewCourt);

                    if (htUserViewCourt != null)
                    {
                        //check result
                        if (!_KRNL.ReturnHashtableOk(htUserViewCourt))
                        {
                            //TOODOO: Might need to start a timer here to be able to retry getting allianceId
                            _KRNL.EC.AddException(new Exception("No viewCourt received... Ouch!!! Need a retry timer here."), this.ToString(), "_getUserAlliance()");
                        }

                        //read Data
                        Hashtable htProfile = htUserViewCourt["profile"] as Hashtable;
                        if (htProfile != null)
                        {
                            //UserProfileItem UPI = new UserProfileItem(_KRNL, htProfile, UVI);
                            UPI.AnalyzeHashtable(_KRNL, htProfile);
                        }
                    }
                }
            }
        }
        #endregion



        #region interface
        #region properties
        public bool UserIsValid
        {
            get
            {
                if (_upiSelectedUser != null)
                {
                    return _upiSelectedUser.UserIsValid;
                }

                return false;
            }
        }

        public string UserValidText
        {
            get
            {
                if (_upiSelectedUser != null &&
                    _upiSelectedUser.FbUid.Trim() != "" &&
                    !_upiSelectedUser.UserIsValid)
                {
                    return string.Concat(DEFAULT_WINDOW_TITLE, " - This FBUid is not allowed. Contact author for permission.");
                }

                return DEFAULT_WINDOW_TITLE;
            }
        }

        public ObservableCollection<UserProfileItem> Users
        {
            get
            {
                return _ocUsers;
            }
        }

        public UserProfileItem SelectedUser
        {
            get
            {
                return _upiSelectedUser;
            }
            set
            {
                #region before user change
                //Clear reports if UserID changed
                if (_upiSelectedUser != null &&
                    _upiSelectedUser.FbUid != value.FbUid)
                {
                    //Clear whatever (Callback delegate? Event?)
                    if (_ocKnights != null)
                    {
                        _saveKnightOptions();
                    }
                }
                #endregion

                _upiSelectedUser = value;

                #region after user change
                _checkSeedExists();

                if (_ocKnights != null)
                {
                    _clearKnights();
                }

                Thread thr = new Thread((ParameterizedThreadStart)delegate
                {
                    _getUserAlliance(ref _upiSelectedUser);
                });
                thr.Start();

                OnPropertyChanged("Users");
                OnPropertyChanged("UserIsValid");
                OnPropertyChanged("UserValidText");
                OnPropertyChanged("CurrentAlliance");
                #endregion
            }
        }

        public string CurrentAlliance
        {
            get
            {
                return _upiSelectedUser.allianceName;
            }
        }

        public int ServerId
        {
            get
            {
                return _intServerId;
            }
            set
            {
                if (value != _intServerId &&
                    value <= constants.MAX_SERVER_NUMBER)
                {
                    #region before user change
                    //Clear whatever (Callback delegate? Event?)
                    if (_ocKnights != null)
                    {
                        _saveKnightOptions();
                    }
                    #endregion

                    //set and save server id
                    _intServerId = value;
                    _KRNL.LAO.SetOption(constants.LAO_DEFAULT_SERVER_ID, _intServerId.ToString());

                    #region after user change
                    //If a user ist selected, get the alliance name of the new server
                    if (_upiSelectedUser != null)
                    {
                        _checkSeedExists();

                        if (_ocKnights != null)
                        {
                            _clearKnights();
                        }

                        //get user profile
                        Thread thr = new Thread((ParameterizedThreadStart)delegate
                        {
                            _getUserAlliance(ref _upiSelectedUser);
                        });
                        thr.Start();

                        //notify UI
                        OnPropertyChanged("CurrentAlliance");
                        OnPropertyChanged("Users");
                    #endregion
                    }
                }
            }
        }
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
